#include "mainwindow.h"

#include <QTreeView>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QHeaderView>
#include <QDebug>

struct Record {
    QString name = "";
    int value = -1;
    QString mac = "";
};

Q_DECLARE_METATYPE(Record)

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QTreeView *view = new QTreeView(this);
    view->header()->setVisible(false);
    setCentralWidget(view);

    QStandardItemModel *model = new QStandardItemModel(this);
//    可以继承QStandardItemModel写insertItems(int position, QList<QStandardItem*> items);
//    appendItems(QList<QStandardItem*> items);
    view->setModel(model);

    for (int i = 0; i < 10; i++) {
        QStandardItem *item = new QStandardItem("test");
        Record info;
        info.name = "dada";
        info.value = 10;
        info.mac = "dawd";
        item->setData(QVariant::fromValue(info), Qt::UserRole + 1000);  // 设置自定义数据
        QStandardItem *item1 = new QStandardItem(QString("child%1").arg(i+1));
        item->appendRow(item1);
        QStandardItem *item2 = new QStandardItem(QString("child%1").arg(i+1));
        QStandardItem *item3 = new QStandardItem(QString("child%1").arg(i+1));
        QList<QStandardItem *> listItems = {item2, item3};
        item1->appendRows(listItems);

        model->appendRow(item);
    }

    view->expandAll();

    connect(view, &QTreeView::clicked, this, [=](const QModelIndex &index){
        auto item = model->itemFromIndex(index);
        QVariant data = item->data(Qt::UserRole + 1000);
        if (data.isValid()) {
            Record tempinfo = data.value<Record>();  // 获取自定义数据
            qDebug() << tempinfo.name << tempinfo.value << tempinfo.mac;
        }
    });
}

MainWindow::~MainWindow()
{

}
